<template>
  <view class="page">
    <my-modal ref="modal" title="授权手机号" :button="[{ text: '点击授权手机号', type: 'gold', plain: false }]" @clickBtn="clickBtn"></my-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {}
  },
  onLoad() {},
  methods: {
    open(param) {
      this.$refs.modal.open({ showClose: this.$format(param, 'showClose', true) })
    },
    close() {
      this.$emit('afterModalClose')
      this.$refs.modal.close()
    },
    async clickBtn() {
      try {
        await this.wxLogin()
        uni.getUserProfile({
          desc: '授权小程序获取手机号', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: res => {
            console.res('getUserProfile', res)
            if (res.encryptedData && res.iv) {
              this.getUserPhone(res.encryptedData, res.iv)
            }
          },
          fail: err => {
            console.err(err)
          }
        })
      } catch (err) {
        console.err('wxLogin', err)
      }
    },
    // 用户授权获取手机号码
    getUserPhone(encryptedData, iv) {
      return new Promise((resolve, reject) => {
        if (!encryptedData || !iv) {
          reject()
          return this.$msg('text', '用户信息不全')
        }

        const baseParam = this.getBase(['token', 'selectuniacid', 'usertoken'])
        if (!baseParam) return reject()

        console.param('用户授权获取手机号码', baseParam)
        Object.assign(baseParam, { encryptedData, iv })
        this.$api
          .getUserPhone(baseParam)
          .then(res => {
            console.res('用户授权获取手机号码', res)
            resolve(res)
          })
          .catch(err => {
            console.err('用户授权获取手机号码', err)
            this.errMsg(err, '用户授权获取手机号码失败')
            reject(err)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
